package it.polimi.swKnights.SWIMv2.servlets.profile;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidConfirmationException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.modifyData.ModifyDataBeanRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ModifyPasswordController
 */
public class ModifyPasswordController extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		ModifyDataBeanRemote modifyBean = this
				.lookUp(ModifyDataBeanRemote.class);
		HttpSession session = request.getSession();
		String password = (String) session.getAttribute("password");
		String username = (String) session.getAttribute("userName");

		// gotten from form
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("password");
		String confPassword = request.getParameter("password_confirmation");

		try
		{
			modifyBean.modifyPassword(username, password, newPassword,
					confPassword, oldPassword);
			session.setAttribute("password", newPassword);
			response.sendRedirect("./modify?status=password-changed");
		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./userHome?error=" + Errors.session);
			e.printStackTrace();
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./userHome?error=" + Errors.notuser);
			e.printStackTrace();
		}
		catch (InvalidConfirmationException e)
		{
			response.sendRedirect("./modify?error=" + Errors.oldpassword);
			e.printStackTrace();
		}
	}

}
